package com.fs.ibox.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.ibox.dao.UserDao;
import com.fs.ibox.service.IdCollectionService;
import com.fs.ibox.service.OrdersService;
import com.fs.ibox.service.UserService;
import com.fs.ibox.util.BeanFactory;
import com.fs.ibox.util.ResponseDataUtil;
import com.fs.ibox.util.ResponseJSONUtil;
import com.fs.ibox.vo.MarketCollection;
import com.fs.ibox.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

@WebServlet(name = "TradeServlet", value = "/TradeServlet/*")
public class TradeServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset = UTF-8");
        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = req.getReader();
        String line = null;
        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());
        //获取请求路径
        String path = req.getPathInfo();
        if("/buy".equals(path)){
            buy(req, resp,js);
        }
    }

    private void buy(HttpServletRequest req, HttpServletResponse resp , JSONObject js) throws IOException {
        UserService bean = BeanFactory.createBean(UserService.class);
        MarketCollection col = js.getObject("col", MarketCollection.class);
        String user = js.getString("buyer");
        Date odate = js.getDate("odate");
        String username = col.getUsername();
        Double price = col.getPrice();
        //余额变动
        Double trade = bean.Trade(username, user, price);
        OrdersService bean1 = BeanFactory.createBean(OrdersService.class);
        //添加记录
        bean1.addOrders(col, user, odate);
        //修改状态
        IdCollectionService bean2 = BeanFactory.createBean(IdCollectionService.class);
        bean2.updateState(username, user, col.getCname(), col.getCid());
        ResponseData responseData = ResponseDataUtil.buildOk(trade);
        ResponseJSONUtil.responseJSON(responseData, resp);
    }
}
